#include "musicplayer.h"
#include "ui_musicplayer.h"
#include <QListWidget>

#include "head.h"
MusicPlayer::MusicPlayer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicPlayer)
{
    ui->setupUi(this);

    ui->tableView->verticalHeader()->setVisible(false);
    //链接 Enter 与 pushbutton
    QShortcut* shortcut = new QShortcut(QKeySequence(Qt::Key_Return), this);
    connect(shortcut, &QShortcut::activated, ui->buttonSearch, &QPushButton::click);




    // 加载QSS文件
    QFile file(":/music.qss");
    if (file.open(QFile::ReadOnly)) {
        QString stylesheet = QString(file.readAll());
        setStyleSheet(stylesheet);
        file.close();
    }
    new QListWidgetItem("首页", ui->listWidget_Music);
    new QListWidgetItem("我的喜欢", ui->listWidget_Music);
    new QListWidgetItem("最近播放", ui->listWidget_Music);
    new QListWidgetItem("我的收藏", ui->listWidget_Music);
   // new QListWidgetItem("歌词", ui->listWidget_Music);

    pModel = new QStandardItemModel(ui->tableView);
    ui->tableView->setModel(pModel);
    ui->tableView->setItemDelegateForColumn(4,new customDelegete);
    titles << "歌名" << "歌手" << "专辑" << "时长" <<"收藏";
    // 设置数据模型的表头
    QStringList list = QStringList() << "歌名" << "专辑" << "歌手" << "时长"<< "收藏";
    pModel->setHorizontalHeaderLabels(list);

        // 初始化数据库操作类
        dDatabase = new databaseOP;
        // 创建表
        QSqlQuery query;
        // 创建表
        QString sql = "CREATE TABLE IF NOT EXISTS music (\
                        id int,\
                        song_name varchar(255),\
                        singer varchar(255),\
                        album varchar(255),\
                        duration varchar(255),\
                        favorite varchar(255)\
                      );";

        // 执行 SQL
        if (!dDatabase->excutSql(query, sql)) {
            qDebug() << "Failed to create table!";
        }

        // 创建表
        QSqlQuery query1;

        // 创建表
        QString sqlRecentPlays  = "CREATE TABLE IF NOT EXISTS recent_plays (\
                        id int,\
                        song_name varchar(255),\
                        singer varchar(255),\
                        album varchar(255),\
                        duration varchar(255),\
                        favorite varchar(255)\
                      );";

        // 执行 SQL
        if (!dDatabase->excutSql(query1, sqlRecentPlays)) {
            qDebug() << "Failed to create table!";
        }

//        QSqlQuery query2;
//        QString deleteQuery = "DELETE FROM recent_plays";
//        if (!query2.exec(deleteQuery)) {
//            qDebug() << "Failed to delete data: " << query2.lastError();
//        } else {
//            qDebug() << "All data deleted from recent_plays table.";
//        }



    musicF1=new MusicForm1(ui->MusicPlayerwidget);
    musicF1->hide();

    musicF2=new MusicForm2(ui->MusicPlayerwidget);
    musicF2->hide();

    musicF3=new MusicForm3(ui->MusicPlayerwidget);
    musicF3->hide();

    musicLy=new MusicLyric(ui->MusicPlayerwidget);
    musicLy->hide();

    //创建一个网络访问管理对象
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));

    playlist = new QMediaPlaylist;
    playlist->setCurrentIndex(1);

    player = new QMediaPlayer;
    player->setPlaylist(playlist);

    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChangedSlot(qint64)));

    player->play();
}

//自定义槽
void MusicPlayer::replyFinished(QNetworkReply* reply)
{
    qDebug()<<"--------\"hello\"--------"<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)<<endl;
//    QNetworkRequest::HttpStatusCodeAttribute网址返回的状态码
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<endl;
        parseJson(reply->readAll());
    }
}


//提取歌曲信息
void MusicPlayer::parseJson(QByteArray byteArray)
{
    unsigned int id = -1;
    QString songName;
    QString albumName;
    QString singerName;
    QString myFavorite="未收藏";
    float duration = -1;

    misicIdList.clear();    //媒体播放id存放链表
    playlist->clear();      //清空播放列表，每次执行前要进行的操作

    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    if(doc.isObject())//问文档内部是否是一个对象？
    {
        QJsonObject obj1 = doc.object();//返回文档内的对象
        if(obj1.contains("result") == false)//问文档对象是否包含result关键字
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue var = obj1.value("result");//获得关键字result对应的结果
        if(var.isObject() == false)
        {
            qDebug()<<"result的值不是一个对象"<<endl;
            return;
        }
        QJsonObject resultObj = var.toObject();//把result的值转为一个对象
        if(resultObj.contains("songs") == false)
        {
            qDebug()<<"JSON对象没有歌曲"<<endl;
            return;
        }
        var = resultObj.value("songs");//得到关键字songs的值
        if(var.isArray())//是否为数组？
        {
            QJsonArray songsArr = var.toArray();//把songs的值转为一个数组
            qDebug()<<"一共搜索到"<<songsArr.size()<<"首歌曲"<<endl;
            for(int i = 0 ; i < songsArr.size() ; i++)
            {
                QJsonObject songObj = songsArr[i].toObject();//把下标为i的元素转为对象
                if(songObj.contains("id"))
                {
                    QJsonValue varID = songObj.value("id");//获取关键字为id的元素的值
                    id = varID.toDouble();//把值转为整数
                }
                if(songObj.contains("name"))
                {
                    QJsonValue varName = songObj.value("name");
                    songName = varName.toString();
                }
                if(songObj.contains("album"))//是否包含专辑
                {
                    QJsonValue varAlbum = songObj.value("album");//得到专辑关键字的值
                    if(varAlbum.isObject())
                    {
                        QJsonObject albumObj = varAlbum.toObject();//把专辑的值转为对象
                        if(albumObj.contains("name"))
                        {
                            QJsonValue varAlbumName =  albumObj.value("name");
                            albumName = varAlbumName.toString();//得到专辑名
                        }
                    }
                }
                if(songObj.contains("artists"))//是否包含作者关键字
                {
                    QJsonValue varArtists = songObj.value("artists");
                    if(varArtists.isArray())//作者的值是否为数组？
                    {
                       QJsonArray arrArtists = varArtists.toArray();
                       for (int i = 0; i < arrArtists.size(); ++i) {//遍历作者数组
                           if(arrArtists[i].isObject())
                           {
                               QJsonObject artistsObj = arrArtists[i].toObject();
                               if(artistsObj.contains("name"))
                               {
                                   QJsonValue varArtistsName = artistsObj.value("name");
                                   singerName+= varArtistsName.toString();//把名字加入到字符串中
                                   singerName+=" ";//中间留一个空格
                               }
                           }
                       }
                    }
                }
                if(songObj.contains("duration"))
                {
                    QJsonValue varDuration = songObj.value("duration");//获取关键字为duration的元素的值
                    duration = varDuration.toInt()/1000/60.0F;//把值转为整数
                }
                qDebug()<<id<<" "<<songName<<" "<<albumName<<" "<<singerName<<" "<<duration<<endl;

                misicIdList.push_back(id);  //存放歌曲id
                playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));

                QStandardItem *item = new QStandardItem(songName);//歌名
                pModel->setItem(i, 0, item);
                item = new QStandardItem(albumName);
                pModel->setItem(i, 1, item);
                item = new QStandardItem(singerName);
                pModel->setItem(i, 2, item);
                item = new QStandardItem(QString("%1").arg(duration));
                pModel->setItem(i, 3, item);
                item = new QStandardItem(QString("%1").arg(myFavorite));
                item->setTextAlignment(Qt::AlignCenter);               // 收藏状态居中
                pModel->setItem(i, 4, item);

                singerName = "";//清空歌手名
            }

        }
    }
}

MusicPlayer::~MusicPlayer()
{
    delete ui;
}

void MusicPlayer::on_horizontalSlider_sliderReleased()
{
    qint64 var = ui->horizontalSlider->value();//得到滑块当前值
    player->setPosition(var);//把滑块当前值作为音乐的播放时间
}



void MusicPlayer::on_buttonPrevious_clicked()
{
    playlist->previous();
}

void MusicPlayer::on_buttonPause_clicked()
{
    // 判断当前播放器的状态
        if (player->state() == QMediaPlayer::PlayingState) {
            // 如果播放器正在播放，则暂停音乐
            player->pause();
            ui->buttonPause->setStyleSheet(
                "border: none;" /* 去除边框 */
                "background-repeat: no-repeat;" /* 不重复 */
                "background-position: center;" /* 居中显示 */
                "background-size: contain;" /* 根据按钮大小缩放图片，保持宽高比 */
                "border-image: url(:/img_1/lib/1zantingtingzhi.png);" /* 暂停状态的图片 */
            );
        } else if (player->state() == QMediaPlayer::PausedState) {
            // 如果播放器已经暂停，则继续播放音乐
            player->play();
            ui->buttonPause->setStyleSheet(
                "border: none;" /* 去除边框 */
                "background-repeat: no-repeat;" /* 不重复 */
                "background-position: center;" /* 居中显示 */
                "background-size: contain;" /* 根据按钮大小缩放图片，保持宽高比 */
                "border-image: url(:/img_1/lib/1bofang.png);" /* 播放状态的图片 */
            );
        }
}

void MusicPlayer::on_buttonNext_clicked()
{
    playlist->next();
}

void MusicPlayer::on_buttonSearch_clicked()
{
    // 获取用户输入的搜索关键字
     QString keyword = ui->lineEdit->text();
     if (keyword.isEmpty()) {
         qDebug() << "Please enter a song name!";
         return;
     }

     // 构建网易云音乐 API 请求 URL
     QString url = QString("http://music.163.com/api/search/get/web?csrf_token=&s=%1&type=1&offset=0&total=true&limit=10")
                       .arg(keyword);

     // 发起 GET 请求
     QNetworkRequest request;
     request.setUrl(QUrl(url));
     manager->get(request);
}

void MusicPlayer::on_listWidget_Music_currentRowChanged(int currentRow)
{
    musicF1->hide();
    ui->tableView->hide();
    musicF2->hide();
    musicLy->hide();
    musicF3->hide();
    if (currentRow == 0)
    {
        ui->tableView->show();
    }
    else if (currentRow == 1)
    {
        musicF1->show();
    }
    else if (currentRow == 2)
    {

        musicF2->show();
       //showRecentPlays(); // 显示最近播放列表
    }
    else if (currentRow == 3)
    {
        musicF3->show();
    }
    else if (currentRow == 4)
    {
        musicLy->show();
    }
}

void MusicPlayer::on_tableView_clicked(const QModelIndex &index)
{
    if(index.column() != 4) // If not the 4th column (Favorite column), do nothing.
    {
        return;
    }

    QVariant ret = pModel->data(index); // Get the current value from the model
    QStandardItem *item = pModel->item(index.row(), index.column());
    QString songName = pModel->item(index.row(), 0)->text(); // Assuming songName is in the first column
    QString singerName = pModel->item(index.row(), 2)->text(); // Assuming singerName is in the third column
    QString albumName = pModel->item(index.row(), 1)->text(); // Assuming albumName is in the second column
    QString duration = pModel->item(index.row(), 3)->text(); // Assuming duration is in the fourth column
    int id = misicIdList[index.row()]; // Get the song's ID

    if (ret == "未收藏") {
        // Change to "已收藏"
        pModel->setItem(index.row(), index.column(), new QStandardItem("已收藏"));

        // Insert song into the database
        QSqlQuery query;
        query.prepare("INSERT INTO music (id, song_name, singer, album, duration, favorite) "
                      "VALUES (:id, :song_name, :singer, :album, :duration, :favorite)");

        query.bindValue(":id", id);
        query.bindValue(":song_name", songName);
        query.bindValue(":singer", singerName);
        query.bindValue(":album", albumName);
        query.bindValue(":duration", duration);
        query.bindValue(":favorite", "已收藏");

        if (!query.exec()) {
            qDebug() << "Failed to insert data: " << query.lastError();
        }
    } else if (ret == "已收藏") {
        // Change to "未收藏"
        pModel->setItem(index.row(), index.column(), new QStandardItem("未收藏"));

        // Delete song from the database
        QSqlQuery query;
        query.prepare("DELETE FROM music WHERE id = :id");
        query.bindValue(":id", id);

        if (!query.exec()) {
            qDebug() << "Failed to delete data: " << query.lastError();
        }
    }
}
void MusicPlayer::on_tableView_doubleClicked(const QModelIndex &index)
{

    playlist->setCurrentIndex(index.row()); // 双击的行数就是播放列表中歌曲的下标
        player->play();

        // 获取歌曲详细信息
        QString songName = pModel->item(index.row(), 0)->text(); // 歌名
        QString singerName = pModel->item(index.row(), 2)->text(); // 歌手
        QString albumName = pModel->item(index.row(), 1)->text(); // 专辑
        QString duration = pModel->item(index.row(), 3)->text(); // 时长
        int id = misicIdList[index.row()]; // 获取歌曲的ID

        // 插入到recent_plays表中
        QSqlQuery query;
        query.prepare("INSERT INTO recent_plays (id, song_name, singer, album, duration, favorite) "
                      "VALUES (:id, :song_name, :singer, :album, :duration, :favorite)");

        query.bindValue(":id", id); // 绑定ID
        query.bindValue(":song_name", songName); // 绑定歌名
        query.bindValue(":singer", singerName); // 绑定歌手
        query.bindValue(":album", albumName); // 绑定专辑
        query.bindValue(":duration", duration); // 绑定时长
        query.bindValue(":favorite", "未收藏"); // 默认值

        // 执行插入操作，并检查错误
        if (!query.exec()) {
            qDebug() << "插入recent_plays失败: " << query.lastError();
        }

        // 获取歌词
        QString url = QString("https://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(id);
        QNetworkRequest request;
        request.setUrl(QUrl(url));
        QNetworkReply* reply = manager->get(request); // 发起网络请求
        connect(reply, &QNetworkReply::finished, this, [this, reply]() { on_buttonLyricsReceived(reply); });


}
void MusicPlayer::on_buttonLyricsReceived(QNetworkReply *reply)
{
    qDebug() << "请求 URL: " << reply->url(); // 输出请求的 URL
      if (reply->error() == QNetworkReply::NoError) {
          QByteArray byteArray = reply->readAll();
          qDebug() << "返回数据: " << byteArray; // 输出返回的数据

          // 调用歌词解析函数
          parseLyrics(byteArray);

      } else {
          qDebug() << "网络请求错误:" << reply->errorString() << " 状态代码：" << reply->error();
          ui->textEditLyrics->setPlainText("网络请求错误");
      }

      reply->deleteLater(); // 释放回复对象
}

void MusicPlayer::parseLyrics(const QByteArray &jsonData)
{
    // 清空歌词容器
    lrcMap.clear();

    // 解析 JSON
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &jsonError);

    if (jsonError.error != QJsonParseError::NoError) {
        qDebug() << "JSON解析错误:" << jsonError.errorString();
        return;
    }

    // 检查根对象
    if (!jsonDoc.isObject()) {
        qDebug() << "顶层不是对象";
        return;
    }

    QJsonObject rootObj = jsonDoc.object();

    // 检查 "lrc" 字段
    if (rootObj.contains("lrc") && rootObj.value("lrc").isObject()) {
        QJsonObject lrcObj = rootObj.value("lrc").toObject();

        // 检查 "lyric" 字段
        if (lrcObj.contains("lyric") && lrcObj.value("lyric").isString()) {
            QString lyricString = lrcObj.value("lyric").toString();

            // 逐行处理歌词
            QStringList lines = lyricString.split("\n");
            for (const QString &line : lines) {
                // 使用正则表达式匹配时间戳
                QRegExp timeRegExp("\$(\\d{2}):(\\d{2}\\.\\d{2})\$");
                int pos = 0;

                // 捕获时间戳和歌词内容
                while ((pos = timeRegExp.indexIn(line, pos)) != -1) {
                    int minutes = timeRegExp.cap(1).toInt();
                    int seconds = timeRegExp.cap(2).toDouble() * 1000; // 将秒转换为毫秒
                    int totalMilliseconds = (minutes * 60 * 1000) + seconds;

                    QString lrcText = line.mid(pos + timeRegExp.cap(0).size()).trimmed(); // 提取歌词文本
                    lrcMap.insert(totalMilliseconds, lrcText); // 保存时间戳和歌词内容

                    pos += timeRegExp.cap(0).size(); // 更新位置继续查找
                }
            }

            // 打印所有歌词
            for (auto it = lrcMap.constBegin(); it != lrcMap.constEnd(); ++it) {
                qDebug() << "时间:" << it.key() << "歌词:" << it.value();
            }

            // 显示歌词到 UI
            QStringList lyricsList;
            for (auto it = lrcMap.constBegin(); it != lrcMap.constEnd(); ++it) {
                lyricsList << it.value(); // 将歌词内容添加到列表中
            }
            ui->textEditLyrics->setPlainText(lyricsList.join("\n")); // 显示到文本框
        } else {
            qDebug() << "未找到歌词内容";
            ui->textEditLyrics->setPlainText("没有找到歌词");
        }
    } else {
        qDebug() << "未找到lrc字段";
        ui->textEditLyrics->setPlainText("未找到lrc字段");
    }
}

//滑块位置
void MusicPlayer::positionChangedSlot(qint64 position)
{
    qDebug()<<position<<endl;
    ui->horizontalSlider->setValue(position);
}

void MusicPlayer::durationChangedSlot(qint64 duration)
{
    qDebug()<<duration<<endl;
    ui->horizontalSlider->setRange(0,duration);//设置滑块的总范围为歌曲的时长
}




